import React, { Component } from 'react';
import { grey400 } from 'material-ui/styles/colors';
import CircularProgress from 'material-ui/CircularProgress';

import Masonry from 'react-masonry-component';
import InfiniteScroll from 'react-infinite-scroller';

import CONFIG from '../../config';
import { moment } from '../Utils/Helper';
import NotificationCard from './NotificationCard';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

export default class Notification extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      nextPageUrl: null,
      isInfiniteLoading: true,
    };
  }

  componentWillMount() {
    let url = CONFIG.apiHost + '/api/n?token=' + this.props.token;
    
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.msg.next_page_url) {
        this.setState({isInfiniteLoading: true})
      }else{
        this.setState({isInfiniteLoading: false})
      }
      this.setState({
        data: res.msg.data,
        nextPageUrl: res.msg.next_page_url
      });
    })
  }

  /**
   * 加载时的动画
   */
  elementInfiniteLoad() {
    return (
      <div className="center-block" style={{width: 32}}>
        <CircularProgress 
          size={32} 
          style={{margin: 8}} 
          thickness={3} 
        /> 
      </div>
    );
  }

  /**
   * 加载更多通知
   */
  handleInfiniteLoad = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.data;

      let request = '&token='+this.props.token;
      let url = this.state.nextPageUrl + request;

      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        setTimeout(() => {
          this.setState({
            nextPageUrl: res.msg.next_page_url,
            data: arr.concat(res.msg.data)
          });
        }, 500)
      })
    }else{
      this.setState({isInfiniteLoading: false});
    }
  };

  /**
   * 删除通知
   */
  handleDel = (id, index, e) => {
    let arr = this.state.data;
    arr.splice(index, 1);

    let url = `${CONFIG.apiHost}/api/n/${id}?token=${this.props.token}`;
    fetch(url, postJsonMethod(null));

    this.setState({data: arr});
  };

  /**
   * 查看活动，通知标记活动状态
   */
  handleClick = (id, index, isDisabled, e) => {
    if (!isDisabled) {
      let arr = this.state.data;
      arr[index].status = 1;

      let url = `${CONFIG.apiHost}/api/n/check/${id}?token=${this.props.token}`;
      fetch(url, getMethod);

      this.setState({data: arr});
    }
  };

  /**
   * 标记已加入状态
   */
  handleClickJoin = (index) => {
    let arr = this.state.data;
    let detail = JSON.parse(arr[index].detail);
    detail.is_joined = 1;
    arr[index].detail = JSON.stringify(detail);
    this.setState({data: arr});
  };

  render() {
    let nullElement = (
      <div style={{width: '100%', textAlign: 'center'}}>
        <p style={{color: grey400}}>已经阅读完所有的通知了</p>
      </div>
    );

    let elements = this.state.data.map((item, index) => {
      let createdAt;
      
      if (!this.nextTimestamp) {
        this.nextTimestamp = moment(item.created_at).unix() - 600;
      }

      let thisTimestamp = moment(item.created_at).unix();
      let secondRange = thisTimestamp - this.nextTimestamp;

      if (index === 0) {
        secondRange = 600;
      }

      if (secondRange >= 600) {
        let a = moment(moment().format('YYYY-MM-DD'));
        let b = moment(moment(item.created_at).format('YYYY-MM-DD'));
        let dayRange = a.diff(b, 'days');
        if (dayRange === 0) {
          createdAt = moment(item.created_at).format('LT')
        } else if (dayRange === 1) {
          createdAt = moment(item.created_at).subtract(0, 'days').calendar()
        } else if (dayRange > 1 && dayRange <= 7) {
          createdAt = moment(item.created_at).format('dddd h:mm')
        } else {
          createdAt = moment(item.created_at).format('lll')
        }
        this.nextTimestamp = moment(item.created_at).unix();
      }

      return (
        <NotificationCard
          key={index}
          item={item}
          index={index}
          createdAt={createdAt}
          token={this.props.token}
          userId={this.props.userId}
          color500={this.props.color500}
          pushTo={this.props.pushTo}
          handleDel={this.handleDel}
          handleClick={this.handleClick}
          handleClickJoin={this.handleClickJoin}
        />
      );
    });

  	return (
      <div className="infinite-container">
        <InfiniteScroll
          pageStart={0}
          loadMore={this.handleInfiniteLoad.bind(this)}
          hasMore={this.state.isInfiniteLoading}
          loader={this.elementInfiniteLoad()}
          initialLoad={false}
          useWindow={true}
          threshold={20}
        >
          <Masonry
            style={{width: '100%'}}
            elementType={'div'}
          >
            {this.state.data.length === 0 ? nullElement : elements}
          </Masonry>
        </InfiniteScroll>
      </div>
  	);
  }
};